package com.example.demo.passwordEncoder;


import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MyMD5PasswordEncoder implements PasswordEncoder {


    /**
     *明文加密
     * @param rawPassword 明文，页面收集的密码
     * @author 陈先生
     * @date 2021/4/2 14:19
     * @return java.lang.String
     * @throws
     */
    @Override
    public String encode(CharSequence rawPassword) {
        try {
            MessageDigest digest=MessageDigest.getInstance("MD5");
            byte [] temp=digest.digest(rawPassword.toString().getBytes());
            return toHexString(temp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     *  
     * @param rawPassword 明文，页面收集的明文
     * @param encodedPassword  密文，数据源的密文
     * @author 陈先生
     * @date 2021/4/2 14:16
     * @return boolean
     * @throws 
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(encode(rawPassword));
    }

    /**
     *
     * @param temp
     * @author 陈先生
     * @date 2021/4/2 14:19
     * @return java.lang.String
     * @throws
     */
    public String toHexString(byte [] temp){
        StringBuilder builder=new StringBuilder("");
        for(byte b : temp){
            String s=Integer.toHexString(b & 0xFF);
            if(s.length()==1){
                builder.append("0");
            }
            builder.append(s);
        }
        return builder.toString();
    }
}
